package com.wisewin.circle.util.tencentyun;

import com.alibaba.fastjson.JSONObject;;
import com.wisewin.circle.util.JedisUtil;
import com.wisewin.circle.util.env.Env;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TencentCloudImUtil {
    private transient Logger log = LoggerFactory.getLogger(this.getClass());

    private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
    private static final String APP_MANAGER = "administrator";
    private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";

    private long sdkAppId = Long.parseLong(Env.getProperty("imAppId"));
    private String key = Env.getProperty("imAppSecretkey");

    /**导入单个帐号*/
    public static final String ACCOUNT_IMPORT = "v4/im_open_login_svc/account_import";
    /**删除帐号*/
    public static final String ACCOUNT_DELETE = "v4/im_open_login_svc/account_delete";
    /**查询帐号*/
    public static final String ACCOUNT_CHECK = "v4/im_open_login_svc/account_check";
    /**设置资料*/
    public static final String PORTRAIT_SET = "v4/profile/portrait_set";
    /**拉取资料*/
    public static final String PORTRAIT_GET = "v4/profile/portrait_get";

    /**
     * 获取腾讯云用户签名
     */
    public String getTxCloudUserSig() {
        String userSig = JedisUtil.get(REDIS_IM_USER_SIG + APP_MANAGER);
        if (StringUtils.isEmpty(userSig)) {
            TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, key);
            userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
            JedisUtil.setEx(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
        }
        return userSig;
    }

    public String getTxCloudUserSig(String userId) {
        String userSig = JedisUtil.get(REDIS_IM_USER_SIG + userId);
        if (StringUtils.isEmpty(userSig)) {
            TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, key);
            userSig = tlsSigApi.genUserSig(userId, 86400);
            JedisUtil.setEx(REDIS_IM_USER_SIG + userId, userSig, 86400L);
        }
        return userSig;
    }

    /**
     * 获取腾讯im请求路径
     */
    private String getHttpsUrl(String imServiceApi, Integer random) {
        return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
                HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
    }

    /**
     * 导入单个账号
     * @param userId 用户id
     */
    public void accountImport(String userId) {
        accountImport(userId, null);
    }

    public void accountImport(String userId, String userName) {
        accountImport(userId, userName, null);
    }

    public void accountImport(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(ACCOUNT_IMPORT, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Identifier", userId);
        if (StringUtils.isNotEmpty(userName)) {
            jsonObject.put("Nick", userName);
        }
        if (StringUtils.isNotEmpty(faceUrl)) {
            jsonObject.put("FaceUrl", faceUrl);
        }
        log.info("腾讯云im导入单个账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im导入单个账号，返回结果：{}", result);
    }

    // 设置资料
    public String portraitSet(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(PORTRAIT_SET, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", userId);
        List<JSONObject> body = new ArrayList<>();
        // 昵称
        JSONObject bodyJsonNick = new JSONObject();
        bodyJsonNick.put("Tag", "Tag_Profile_IM_Nick");
        bodyJsonNick.put("Value", userName);
        body.add(bodyJsonNick);
        // 头像
        JSONObject bodyJsonImage = new JSONObject();
        bodyJsonImage.put("Tag", "Tag_Profile_IM_Image");
        bodyJsonImage.put("Value", faceUrl);
        body.add(bodyJsonImage);
        jsonObject.put("ProfileItem", body);
        log.info("腾讯云im设置资料，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im设置资料，返回结果：{}", result);
        return result;
    }

    // 获取资料
    public String portraitGet(String userId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(PORTRAIT_GET, random);
        JSONObject jsonObject = new JSONObject();
        List<String> lstAccount = new ArrayList<>();
        lstAccount.add(userId);
        jsonObject.put("To_Account", lstAccount);
        List<String> body = new ArrayList<>();
        body.add("Tag_Profile_IM_Nick");
        body.add("Tag_Profile_IM_Image");
        jsonObject.put("TagList", body);
        log.info("腾讯云im设置资料，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im设置资料，返回结果：{}", result);
        return result;
    }

    /**
     * 删除账号
     * @param userIds 用户id集合
     */
    public void accountDelete(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(ACCOUNT_DELETE, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
        log.info("腾讯云im删除账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im删除账户，返回结果：{}", result);
    }

    /**
     * 查询账号是否已经导入im
     * @param userIds 用户id集合
     */
    public String accountCheck(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(ACCOUNT_CHECK, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CheckItem", getUserIdJsonList(userIds));
        log.info("腾讯云im查询账号，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.doPost2(httpsUrl, jsonObject);
        log.info("腾讯云im查询账号，返回结果：{}", result);
        return result;
    }

    private List<JSONObject> getUserIdJsonList(List<String> userIds) {
        return userIds.stream().map(v -> {
            JSONObject userIdJson = new JSONObject();
            userIdJson.put("UserID", v);
            return userIdJson;
        }).collect(Collectors.toList());
    }
}
